package com.liuyjy.encryptDecrypt;

import com.liuyjy.base.common.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author liuyjy
 * @Date 2025/2/20 9:41
 * @Description: 默认AES加解密处理器（生产环境应从安全存储获取密钥）
 **/
@Slf4j
@Component
public class DefaultCryptoProvider implements CryptoProvider {

    private final Map<String, String> keyStore = new ConcurrentHashMap<>();


    //    @Autowired
//    private KeyVaultService vaultService;
//
//    /**
//     * 动态密钥加载
//     */
//    @PostConstruct
//    public void loadKeys() {
//        keyStore.put("AES-v2", vaultService.getKey("aes_v2"));
//    }
//    @PostConstruct
//    public void init() {
//       keyStore.put("AES-default", "your-secret-key-here");
//    }
//    public DefaultCryptoProcessor(@Value("${crypto.keys.aes.default:}") String defaultKey) {
//        keyStore.put("AES-default", defaultKey);
//    }

    @Override
    public String encrypt(String content, Encrypt meta) {
        String key = getKey(meta.algorithm(), meta.keyVersion());
        // 实际加密逻辑实现（示例）
        //return "ENC(" + Base64.getEncoder().encodeToString(content.getBytes()) + ")";
        return AESUtil.encrypt(content);
    }

    @Override
    public String decrypt(String content, Decrypt meta) {
        String key = getKey(meta.algorithm(), meta.keyVersion());
        // 实际解密逻辑实现（示例）
//        String payload = content.replaceAll("^ENC\\((.*)\\)$", "$1");
//        return new String(Base64.getDecoder().decode(payload));
        return AESUtil.decrypt(content);
    }

    //    private String getKey(String algorithm, String version) {
//        String key = keyStore.get(algorithm + "-" + version);
//        if (key == null) throw new CryptoException("密钥不存在");
//        return key;
//    }
    private String getKey(String algorithm, String version) {
        return keyStore.getOrDefault(algorithm + "-" + version,
                keyStore.get("AES-default"));
    }
}
